var express = require('express');
var router = express.Router();
const sql = require('../db')

/* GET users listing. */
router.get('/', function(req, res, next) {
  // res.send('respond with a resource');
  sql('select * from users', [])
  .then((result) => {
      res.json({ code: 200, data: result })
  }).catch((err) => {
      console.log(err)
      res.json({ code: 500, data: '程序错误' })
  })
});

// 增删改查

// 获取指定id的用户
router.get('/:id', (req, res) => {
    if (!isNaN(req.params.id)) {
        sql('select * from users where id=?', req.params.id)
            .then((result) => {
                res.json({ code: 200, data: result })
            })
            .catch(() => {
                res.json({ code: 500, data: '程序错误' })
            })
    } else {
        res.json({ code: 400, data: '参数错误' })
    }
})

// 新增用户
router.post('/', (req, res) => {
    if (req.body) {
        sql('insert into users set ?', req.body)
            .then((result) => {
                if (result.affectedRows > 0) {
                    res.json({ code: 200, data: '新增成功' })
                } else {
                    res.json({ code: 400, data: '新增失败' })
                }
            })
            .catch(() => {
                res.json({ code: 500, data: '程序错误' })
            })
    }
})

// 修改用户
router.put('/:id', (req, res) => {
    if (req.body) {
        sql('update users set name=? time=? status=? major=? where id=?',
            [req.body.name, req.body.time, req.body.status, req.body.major, req.params.id])
            .then((result) => {
                if (result.affectedRows > 0) {
                    res.json({ code: 200, data: '修改成功' })
                } else {
                    res.json({ code: 400, data: '修改失败' })
                }
            })
            .catch(() => {
                res.json({ code: 500, data: '程序错误' })
            })
    } else {
        res.json({ code: 500, data: '参数错误' })
    }
})

// 删除用户
router.delete('/:id', (req, res) => {
    if (!isNaN(req.params.id)) {
        sql('delete from users where id=?', req.params.id)
            .then((result) => {
                if (result.affectedRows > 0) {
                    res.json({ code: 200, data: '删除成功' })
                } else {
                    res.json({ code: 400, data: '删除失败' })
                }
            })
            .catch(() => {
                res.json({ code: 500, data: '程序错误' })
            })
    } else {
        res.json({ code: 500, data: '参数错误' })
    }
})

module.exports = router;
